package service

import (
	"database/sql"
	"duoke/internal/dao"
	"duoke/utils/gconv"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/grand"
	"math"
)

var Merchant = new(merchantService)

type merchantService struct{}

func (s *merchantService) Money(c *gin.Context, uid int, money float64, remark string) error {
	var res sql.Result
	var err error
	if money > 0 {
		res, err = dao.User.Ctx(c).Where("id", uid).Unscoped().Increment("money", math.Abs(money))
	} else {
		res, err = dao.User.Ctx(c).Where("id", uid).Unscoped().Decrement("money", money)
	}
	if err != nil {
		return err
	}
	if rows, _ := res.RowsAffected(); rows == 0 {
		return errors.New("用户金额操作失败")
	}
	dao.UserMoneyLog.Ctx(c).Data(g.Map{
		"type":       "money",
		"user_id":    uid,
		"order_no":   gtime.Now().Format("YmdHis") + "ur" + gconv.String(grand.N(0, 99)),
		"amount":     money,
		"status":     1,
		"remark":     remark,
		"created_at": gtime.Now().Timestamp(),
	}).Unscoped().Insert()
	return nil
}
